package service

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"context"
	"fmt"
)

func AddBrand(b model.Brand, cs []string) (int, error) {

	fail := func(err error) (int, error) {
		return 0, fmt.Errorf("AddBrand: %v", err)
	}
	ctx := context.Background()
	var err error
	tx, err := common.DB.BeginTx(ctx, nil)
	if err != nil {
		return fail(err)
	}
	/**
		Defer the transaction’s rollback. If the transaction succeeds,
	it will be committed before the function exits, making the deferred rollback call a no-op.
		If the transaction fails it won’t be committed,
	meaning that the rollback will be called as the function exits.
	*/
	defer tx.Rollback()

	id, err := data.AddBrand(tx, b)
	if err != nil {
		return fail(err)
	}
	// 插入品牌分类中间表
	err = data.AddCategoryBrand(tx, id, b.Name, cs)

	if err != nil {
		return fail(err)
	}
	// 成功，提交事务
	if err = tx.Commit(); err != nil {
		return fail(err)
	}
	return id, nil
}

func UpdateBrand(b model.Brand, needUpdateCategory bool, cs []string) (int, error) {

	fail := func(err error) (int, error) {
		return 0, fmt.Errorf("UpdateBrand: %v", err)
	}
	ctx := context.Background()
	var err error
	tx, err := common.DB.BeginTx(ctx, nil)
	if err != nil {
		return fail(err)
	}
	/**
		Defer the transaction’s rollback. If the transaction succeeds,
	it will be committed before the function exits, making the deferred rollback call a no-op.
		If the transaction fails it won’t be committed,
	meaning that the rollback will be called as the function exits.
	*/
	defer tx.Rollback()

	id, err := data.UpdateBrand(tx, b)
	if err != nil {
		return fail(err)
	}
	if needUpdateCategory {
		// 删除已有的关联表记录
		err = data.DeleteCategoryBrand(tx, id)
		if err != nil {
			return fail(err)
		}
		err = data.AddCategoryBrand(tx, id, b.Name, cs)
		if err != nil {
			return fail(err)
		}
	}
	// 成功，提交事务
	if err = tx.Commit(); err != nil {
		return fail(err)
	}
	return id, nil
}
